package com.atwisdom.star.core.bsl.planner.Impl;

import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.vo.ModelType;
import com.atwisdom.star.core.bsl.planner.MrpLogBslService;
import com.atwisdom.star.core.bsl.planner.entity.MrpLog;
import com.atwisdom.star.core.dsl.modelClass.hier.HierInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.logic.Impl.LogicInstanceDslServiceImpl;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Data
@Service
@NoArgsConstructor
public class MrpLogBslServiceImpl implements MrpLogBslService {
    private LogicInstanceDslServiceImpl logicInstanceDslService;

    @Autowired
    public void setLogicInstanceDslService(LogicInstanceDslServiceImpl logicInstanceDslService) {
        this.logicInstanceDslService = logicInstanceDslService;
    }

    private HierInstanceDslService hierInstanceDslService;

    @Autowired
    public void setHierInstanceDslService(HierInstanceDslService hierInstanceDslService) {
        this.hierInstanceDslService = hierInstanceDslService;
    }

    //日志
    private List<MrpLog> mrpLogs = new ArrayList<>();

    //由前羰传递的执行mrp日志Id;
    private int mrpId;


    @Override
    public void initMrpLog(int mrpId) {
        this.mrpId = mrpId;
        this.mrpLogs = new ArrayList<>();
    }

    /**
     * 构建MRP 日志
     *
     * @param status 状态
     * @param msg    信息
     */
    public void buildMrpLog(int status, String msg) {
        MrpLog mrpLog = new MrpLog();
        mrpLog.setMrpId(this.mrpId);
        mrpLog.setStatus(status);
        mrpLog.setMsg(msg);
        this.mrpLogs.add(mrpLog);
    }

    /**
     * 更新mrp 日志
     *
     * @param status 0:初始化，1：执行中，2：执行失败，3、执行完成
     * @param msg    执行过程备注信息
     */
    public void updateMrpLog(int status, String msg) {
        String className = "mrpLog";
        JSONObject jsonObject = new JSONObject();
        JSONObject values = new JSONObject();
        values.put("status", status);
        jsonObject.put("id", this.mrpId);
        jsonObject.put("className", className);
        jsonObject.put("values", values);
        this.logicInstanceDslService.updateById(jsonObject);
        JSONObject hierInstanceJson = new JSONObject();
        hierInstanceJson.put("parentId", "root");
        hierInstanceJson.put("containerId", mrpId);
        hierInstanceJson.put("containerModel", ModelType.Logic.getCode());
        hierInstanceJson.put("className", className);
        JSONObject subValues = new JSONObject();
        subValues.put("remark", msg);
        hierInstanceJson.put("values", subValues);
        this.hierInstanceDslService.addChild(hierInstanceJson);
    }

    /**
     * 批量更新日志
     */
    public void batchUpdateMrpLog() {
        this.mrpLogs.forEach(m -> {
            this.updateMrpLog(m.getStatus(), m.getMsg());
        });
    }
}
